package com.joy.joyusers.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joy.joyusers.common.BaseResponse;
import com.joy.joyusers.common.ErrorCode;
import com.joy.joyusers.common.ResultUtils;
import com.joy.joyusers.excption.BusinessException;
import com.joy.joyusers.model.VO.TeamUserVO;
import com.joy.joyusers.model.domain.Team;
import com.joy.joyusers.model.domain.User;
import com.joy.joyusers.model.domain.UserTeam;
import com.joy.joyusers.model.dto.TeamQuery;
import com.joy.joyusers.model.request.*;
import com.joy.joyusers.service.TeamService;
import com.joy.joyusers.service.UserService;
import com.joy.joyusers.service.UserTeamService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/team")
@CrossOrigin()
@Api("队伍管理")
@Slf4j
public class TeamController {

    @Resource
    private TeamService teamService;

    @Resource
    private UserService userService;

    @Resource
    private UserTeamService userTeamService;

    /**
     * 创建队伍接口
     * @param teamAddRequest
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        System.out.println(teamAddRequest);
        if (teamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登录用户
        User loginUser = userService.getCurrentLoginUser(request);
        // 创建队伍
        Team team = new Team();
        // 拷贝赋值, 从原对象复制到目的对象中
        BeanUtils.copyProperties(teamAddRequest, team);
        long teamId = teamService.addTeam(team, loginUser);
        return ResultUtils.success(teamId);
    }

    /**
     * 删除队伍接口
     * @param id
     * @return
     */
    @PostMapping("/del")
    public BaseResponse<Boolean> delTeam(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean delruselt = teamService.removeById(id);
        if (!delruselt) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 修改接口
     * @param team
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest team, HttpServletRequest request) {
        if (team == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登录用户信息
        User loginUser = userService.getCurrentLoginUser(request);
        // 传入修改接口
        boolean update = teamService.updateTeam(team, loginUser);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "修改失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 获取team接口
     * @param teamId
     * @return
     */
    @GetMapping ("/get")
    public BaseResponse<Team> getTeamById(long teamId) {
        if (teamId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(teamId);
        System.out.println(team.toString());
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "查询失败");
        }
        return ResultUtils.success(team);
    }

    /**
     * 查询队伍列表接口
     * @param teamQuery
     * @return
     */
    @GetMapping("/list/test")
    public BaseResponse<List<Team>> testGetTeamList(TeamQuery teamQuery) {
        if (teamQuery == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        // 复制参数到我们创建的team里面
        BeanUtils.copyProperties(teamQuery, team);
        // 参数就是 team 里面设置了什么值就会根据这个值来查询数据库
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        List<Team> list = teamService.list(queryWrapper);
        return ResultUtils.success(list);
    }

    /**
     * 查询队伍列表接口
     * @param teamQuery
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> getTeamList(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登录用户信息
        User currentLoginUser = userService.getCurrentLoginUser(request);
        System.out.println("当前登录用户" + currentLoginUser.getId());
        boolean isAdmin = userService.isAdmin(request);
        List<TeamUserVO> list = teamService.listTeam(teamQuery, isAdmin);
        return ResultUtils.success(list);
    }

    /**
     * 获取我创建队伍接口
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list/my")
    public BaseResponse<List<TeamUserVO>> getMyCreateTeamList(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登录用户信息
        boolean isAdmin = true;
        User currentLoginUser = userService.getCurrentLoginUser(request);
        teamQuery.setUserId(currentLoginUser.getId());  // 传入当前登录用户id
        List<TeamUserVO> list = teamService.listTeam(teamQuery, isAdmin);
        return ResultUtils.success(list);
    }

    /**
     * 获取我加入队伍接口
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list/myJoin")
    public BaseResponse<List<TeamUserVO>> getMyJoinTeamList(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前用户信息
        User currentLoginUser = userService.getCurrentLoginUser(request);
        // 用user_id去查询关系库，看看有多少条数据
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",currentLoginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        // 取出不重复的队伍id，去重防止脏数据, 按user_id分组就好
        Map<Long, List<UserTeam>> listMap = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        // 把key 也就是 teamid全取出来
        List<Long> idList = new ArrayList<>(listMap.keySet());
        // 按 id 列表查询 TeamUser 关系表
        teamQuery.setIdList(idList);
        List<TeamUserVO> list = teamService.listTeam(teamQuery, true);
        return ResultUtils.success(list);
    }



    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> getTeamListPage(TeamQuery teamQuery) {
        if (teamQuery == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        // 复制参数到我们创建的team里面
        BeanUtils.copyProperties(teamQuery, team);
        // 新建分页对象
        Page<Team> page = new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize());

        // 参数就是 team 里面设置了什么值就会根据这个值来查询数据库
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        // 查询，传入分页参数和查询数据参数
        Page<Team> pageResult = teamService.page(page, queryWrapper);
        return ResultUtils.success(pageResult);
    }

    /**
     * 创建队伍接口
     * @param teamJoinRequest 用户传入的加入队伍参数
     * @return
     */
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        System.out.println("控制器的参数" + teamJoinRequest.getId());
        if (teamJoinRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登录的用户
        User loginUser = userService.getCurrentLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        boolean result = teamService.joinTeam(teamJoinRequest, loginUser);
        return ResultUtils.success(result);
     }

    /**
     * 退出队伍
     * @param teamQuitRequest
     * @param request
     * @return
     */
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        System.out.println(teamQuitRequest.toString());
        // 校验队伍信息
        if (teamQuitRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登录的用户
        User loginUser = userService.getCurrentLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        boolean result = teamService.quitTeam(teamQuitRequest, loginUser);
        return ResultUtils.success(result);
    }


    /**
     * 解散队伍接口
     * @param id
     * @return
     */
    @PostMapping("/rel")
    public BaseResponse<Boolean> relaeseTeam(@RequestBody TeamDelRequest teamdelRequest, HttpServletRequest request) {
        long id = teamdelRequest.getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getCurrentLoginUser(request);
        boolean delruselt = teamService.deleteTeam(id, loginUser);
        if (!delruselt) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
        return ResultUtils.success(true);
    }


}
